package com.zhiyizhen.handheld.component.pharmacy;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.ImageLoader;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.StringUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.event.AddGiveRecordEvent;
import com.zhiyizhen.handheld.common.event.PharmacyStatusEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.bean.EnumsBean;
import com.zhiyizhen.handheld.component.pharmacy.adapter.GiveDetailAdapter;
import com.zhiyizhen.handheld.component.pharmacy.api.IGiveDosageService;
import com.zhiyizhen.handheld.component.pharmacy.bean.GiveDetailBean;
import com.zhiyizhen.handheld.component.pharmacy.bean.RejectDeliveryReq;
import com.zhiyizhen.handheld.databinding.FragmentGiveDosageDetailBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;

public class GiveDosageDetailFragment extends BaseFragment {
    private FragmentGiveDosageDetailBinding binding;
    private LoginBean loginBean;

    private String orderId;
    private EnumsBean enumsBean;
    private RecyclerView mRecyclerView;
    private GiveDetailAdapter giveDetailAdapter;

    public void setExtraData(EnumsBean enumsBean, String orderId) {
        this.orderId = orderId;
        this.enumsBean = enumsBean;
        getDetail(orderId);
        binding.contentLayout.setVisibility(View.VISIBLE);
        binding.emptyView.setVisibility(View.GONE);
    }

    public void setEmptyData() {
        binding.contentLayout.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentGiveDosageDetailBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 等视图加载完成后获取父容器尺寸
        binding.parentLayout.post(() -> {
            if (binding.parentLayout.getParent() instanceof View) {
                View parentView = (View) binding.parentLayout.getParent();
                // 等待父容器完成测量
                parentView.post(() -> {
                    // 设置固定尺寸
                    ViewGroup.LayoutParams params = binding.parentLayout.getLayoutParams();
                    params.width = LinearLayout.LayoutParams.MATCH_PARENT;
                    params.height = LinearLayout.LayoutParams.MATCH_PARENT;
                    binding.parentLayout.setLayoutParams(params);
                });
            }
            binding.contentLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        });

        loginBean = DataCache.getLoginBean();
        initView();
    }

    private void initView() {
        mRecyclerView = binding.recyclerView;
        giveDetailAdapter = new GiveDetailAdapter(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        binding.rejectDosageBtn.setOnClickListener(v -> showRejectDialog());
        binding.giveDosageBtn.setOnClickListener(v -> showGiveDialog());
    }

    private CommonDialog dialog;

    public void showGiveDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_give_dosage, (ViewGroup) getActivity().getWindow().getDecorView(), false);

        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> reject("2", ""));
    }

    public void showRejectDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_reject_dosage, (ViewGroup) getActivity().getWindow().getDecorView(), false);

        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        EditText refuseReasonEdit = view.findViewById(R.id.refuse_reason_edit);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String reason = refuseReasonEdit.getText().toString().trim();
            if (TextUtils.isEmpty(reason)) {
                ToastUtil.showShort("请输入驳回原因！");
                return;
            }
            reject("3", reason);
        });
    }

    private void setData(GiveDetailBean data) {
        if ("1".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_man, binding.genderImg);
        } else if ("2".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_woman, binding.genderImg);
        } else {
            ImageLoader.load(getContext(), R.drawable.icon_unknow, binding.genderImg);
        }
        binding.genderTv.setText(StringUtil.getGender(data.getPatientGender(), enumsBean));

        binding.userNameTv.setText(data.getPatientName());
        binding.doctorNameTv.setText(data.getDoctorName());
        binding.ageTv.setText(StringUtil.getAge(data.getAgeYear(), data.getAgeMonth()));
        if (data.getWeight() != null) {
            binding.weightTv.setText(data.getWeight() + "kg");
            binding.divideLeftOfWeight.setVisibility(View.VISIBLE);
        } else {
            binding.weightTv.setText(null);
            binding.divideLeftOfWeight.setVisibility(View.GONE);
        }

        if (data.getSystolicBp() != null && data.getDiastolicBp() != null) {
            binding.bloodPressureTv.setText(data.getSystolicBp() + "/" + data.getDiastolicBp() + " mmHg");
            binding.divideLeftOfBlood.setVisibility(View.VISIBLE);
        } else {
            binding.bloodPressureTv.setText(null);
            binding.divideLeftOfBlood.setVisibility(View.GONE);
        }
        binding.phoneTv.setText(data.getPatientPhone());
        binding.deptNameTv.setText(data.getDeptName());
        binding.deptNameTv.setText(data.getDeptName());
        binding.diagnosisTv.setText(data.getDiagnosis());
        binding.diagnosisTimeTv.setText(data.getDiagnosisTime());

        giveDetailAdapter.setDatas(data.getRxList());
        mRecyclerView.setAdapter(giveDetailAdapter);

        if (TextUtils.equals(data.getDeliveryStatus(), "2") || TextUtils.equals(data.getDeliveryStatus(), "3")) {
            binding.rejectDosageBtn.setVisibility(View.GONE);
            binding.giveDosageBtn.setVisibility(View.GONE);
        } else {
            binding.rejectDosageBtn.setVisibility(View.VISIBLE);
            binding.giveDosageBtn.setVisibility(View.VISIBLE);
        }
    }

    private void getDetail(String orderId) {
        ServiceFactory.getService(IGiveDosageService.class)
                .getDispenseDetail(loginBean.getToken(), loginBean.getClinicId(), orderId)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<GiveDetailBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            setData(responseData.getData());
                        }
                    }
                });
    }

    private void reject(String status, String reason) {
        RejectDeliveryReq rejectDeliveryReq = new RejectDeliveryReq();
        rejectDeliveryReq.setOrderId(orderId);
        rejectDeliveryReq.setDeliveryStatus(status);
        if (!TextUtils.isEmpty(reason)) {
            rejectDeliveryReq.setRefuseReason(reason);
        }
        ServiceFactory.getService(IGiveDosageService.class)
                .rejectDelivery(loginBean.getToken(), loginBean.getClinicId(), rejectDeliveryReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        EventBus.getDefault().post(new AddGiveRecordEvent());

                        binding.rejectDosageBtn.setVisibility(View.GONE);
                        binding.giveDosageBtn.setVisibility(View.GONE);
                        EventBus.getDefault().post(new PharmacyStatusEvent(PharmacyStatusEvent.TYPE_GIVE, orderId, status));


                        dialog.dismiss();
                    }
                });
    }


}
